<template>
  <div
    v-for="(forms, index) in formList"
    :key="index + 'key'"
    class="card-list"
  >
    <el-card :key="index" class="card">
      <template #header>
        <div class="card-header">
          <div class="titles">第{{ numberToChinese(index + 1) }}完成单位</div>
          <el-button
            v-if="index != 0"
            :disabled="isDisabled"
            @click="remove(index)"
          >
            移除
          </el-button>
        </div>
      </template>
      <el-form
        ref="formRef9"
        :model="forms"
        :rules="rules"
        class="form-inline mt20"
        label-width="auto"
        label-position="top"
        :disabled="isDisabled"
      >
        <el-form-item
          v-for="(item, j) in form9"
          :key="j"
          :label="item.label"
          :prop="item.prop"
        >
          <!-- input -->
          <el-input
            v-if="item.type === 'input'"
            v-model="forms[item.prop]"
            placeholder="请输入"
            :disabled="item.isDisabled"
            clearable
          />
          <!-- select -->
          <el-select
            v-if="item.type === 'select'"
            v-model="forms[item.prop]"
            :filterable="item.isSearch"
            placeholder="请选择"
          >
            <el-option
              v-for="x in item.options"
              :key="x.value"
              :label="x.label"
              :value="x.value"
            />
          </el-select>

          <!-- textarea -->
          <el-input
            v-if="item.type === 'textarea'"
            v-model="forms[item.prop]"
            placeholder="请输入"
            :rows="4"
            type="textarea"
            clearable
          />

          <!-- date -->
          <el-date-picker
            v-if="item.type === 'date'"
            v-model="forms[item.prop]"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="主要贡献:" prop="k" style="grid-column: span 3">
          <el-input
            v-model="forms.k"
            placeholder="请输入"
            :rows="6"
            type="textarea"
            clearable
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <el-button
    type="primary"
    text
    :icon="Plus"
    :disabled="isDisabled"
    @click="addCard"
  >
    增加完成单位
  </el-button>
</template>

<script setup lang="ts">
  import {
    ref,
    reactive,
    defineExpose,
    defineProps,
    withDefaults,
    onMounted,
    watch,
  } from 'vue'
  import { form9 } from '../table/column'
  import { Delete, Plus } from '@element-plus/icons-vue'
  import { useAchievementAwardStore } from '@/store/modules/achievementAward'
  import { storeToRefs } from 'pinia'
  import { useDictStore } from '@/store/modules/dict'
  import { isPhone } from '@/utils/validate'

  const validatePhone = (rule, value, callback) => {
    if (value && !isPhone(value)) {
      callback(new Error('请输入正确的手机号'))
    } else {
      callback()
    }
  }
  const dictStore = useDictStore()

  const props = withDefaults(
    defineProps<{
      isDisabled?: boolean
      isUpdate?: boolean
    }>(),
    {
      isDisabled: false,
      isUpdate: false,
    }
  )

  const formRef9 = ref()
  const store = useAchievementAwardStore()
  const { UserList, DeptList, eduList, allForm } = storeToRefs(store)
  const getOptions = computed(() => ({
    a: DeptList.value || [],
    b: UserList.value || [],
  }))
  watch(
    [UserList, DeptList],
    () => {
      form9.forEach((item) => {
        item.options = getOptions.value[item.prop] || []
      })
    },
    { deep: true, flush: 'post' }
  )

  watch(
    () => props.isUpdate,
    (val) => {
      formList.value = JSON.parse(allForm.value.majorCompleteUnits ?? '[]')
    }
  )
  const rules = reactive({ e: [{ validator: validatePhone, trigger: 'blur' }] })
  const formItem = ref({
    a: '',
    b: '',
    c: '',
    d: '',
    e: '',
    f: '',
    g: '',
    h: '',
    i: '',
    j: '',
    k: '',
  })
  const formList = ref([])
  formList.value.push(formItem.value)

  const addCard = () => {
    formItem.value = {
      a: '',
      b: '',
      c: '',
      d: '',
      e: '',
      f: '',
      g: '',
      h: '',
      i: '',
      j: '',
      k: '',
    }
    formList.value.push(formItem.value)
  }

  const remove = (index) => {
    formList.value.splice(index, 1)
  }
  const validFormItem = async () => {
    const ok = []
    try {
      await Promise.all(
        formRef9.value.map(async (item) => {
          try {
            const valid = await item.validate()
            if (valid) {
              ok.push('ok')
            }
          } catch (error) {
            console.log(error)
          }
        })
      )
    } catch (e) {
      return false
    }

    return ok
  }
  const { addForm } = store
  const submit = async () => {
    // console.log(formRef9.value)
    // const ok = []
    // await formRef9.value.forEach((item) => {
    //   item.validate((valid) => {
    //     if (valid) {
    //       console.log('submit!')
    //       ok.push('ok')
    //     }
    //   })
    // })

    const ok = await validFormItem()
    if (ok.length === formRef9.value.length) {
      const obj = { majorCompleteUnits: JSON.stringify(formList.value) }
      addForm(obj)
    }
    // if (ok.length == formRef9.value.length) {
    //   console.log('ok')
    // }
    // formRef9.value.validate((valid) => {
    //   if (valid) {
    //     console.log('submit!')
    //     return formInline.value
    //   } else {
    //     console.log('error submit!!')
    //     return false
    //   }
    // })
  }

  function numberToChinese(num) {
    // 定义一个数组来存储数字对应的汉字
    const chineseNumbers = [
      '零',
      '一',
      '二',
      '三',
      '四',
      '五',
      '六',
      '七',
      '八',
      '九',
    ]
    // 返回对应的汉字
    return chineseNumbers[num]
  }

  onMounted(() => {
    // if (props.formData.length != 0) {
    //   formList.value = props.formData
    // }
  })
  defineExpose({
    submit,
  })
</script>

<style scoped lang="scss">
  .form-inline {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-row-gap: 16px;
    grid-column-gap: 20px;
    :deep(.el-form-item__label) {
      padding: 0 5px 0 0;
    }

    :deep(.el-form-item) {
      margin-right: 0px;
      margin-bottom: 0px;
    }
  }

  .mt20 {
    margin-top: 20px;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .card-list {
    margin-top: 20px;
  }
</style>
